package com.example.server.server;

import com.example.api.api.common.RpcRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author heyuduo
 * @date 2022/6/18 16:35
 */
@Slf4j
public class RpcServerProcessor implements Runnable {

    private Socket socket;

    private Map<String, Object> serviceRegistCenter;

    public RpcServerProcessor(Socket socket, Map<String, Object> serviceRegistCenter) {
        this.socket = socket;
        this.serviceRegistCenter = serviceRegistCenter;
    }

    @Override
    public void run() {
        //  获取客户端传输对象,并反序列化
        try (ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream()); 
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream())) {
            RpcRequest rpcRequest = (RpcRequest) inputStream.readObject();
            log.info("ClassName:{}", rpcRequest.getClassName());
            log.info("[{}] 服务端反序列化完毕", LocalDateTime.now());
            Object obj = invoke(rpcRequest);
            log.info("[{}] 服务端调用完毕", LocalDateTime.now());
            objectOutputStream.writeObject(obj);
            objectOutputStream.flush();
            log.info("[{}] 服务端序列化完毕——将结果发送给客户端", LocalDateTime.now());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Object loadBalance(String className) {
        return serviceRegistCenter.get(className);
    }

    private Object invoke(RpcRequest rpcRequest) throws Exception {
        Object[] args = rpcRequest.getParameters();
        Class<?>[] types = rpcRequest.getParameterTypes();
        String className = rpcRequest.getClassName();
        // 服务发现,负载均衡
        Object service = loadBalance(className);
        // 服务调用
        Method method = service.getClass().getMethod(rpcRequest.getMethodName(), types);
        return method.invoke(service, args);

    }
}